<?php
/*
*	Kleophatra - Open Source Content Management System
*	------------------------------------------------------------------------
*	Copyright (C) 2007-2010, Sergio Milardovich <smilardovich@yahoo.com.ar>
*	This program is Free Software.
*
*	@package	Kleophatra
*	@subpackage	/lib
*	@license	http://www.gnu.org/copyleft/gpl.html GNU/GPL License 2.0
*	@author		Sergio Milardovich <smilardovich@yahoo.com.ar>
*	@link		http://www.kleophatra.org
*/
require_once KLEO_LIB_DIR.'paginate.lib.php';
class kleoaccounts extends kleopaginator{

/*
 *	This function generates the salt code when we register a new user
*/
	function generate_salt($count = 16){
		$salt = array('a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9','0');

		$o;
		for($i=0;$i<$count;$i++){
			$o .= $salt[array_rand($salt)];
		}

		return $o;
	}
	
	function get_username($id){

		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE uid = $id LIMIT 1");
		
		$row = $this->fetch_array($query);
		return $row['username'];

	}

	function get_username_avatar($id){
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_profiles, ".KLEO_TABLE_PREFIX."users WHERE ".KLEO_TABLE_PREFIX."users.uid = ".KLEO_TABLE_PREFIX."users_profiles.uid AND ".KLEO_TABLE_PREFIX."users_profiles.uid = $id LIMIT 1");
		$row = $this->fetch_array($query);
		$try_gravatar = 'http://gravatar.com/avatar/'.md5($row['email']).'?default='.urlencode(KLEO_SITEURL.'/media/avatars/'.KLEO_DEFAULT_AVATAR);
		if($row['avatar'] == 'media/avatars/default.png' or $row['avatar'] == 'default.png'){
			$avatar = $try_gravatar;
		} else {
			$avatar = 'media/avatars/'.$row['avatar'];
		}
		return $avatar;
 	}

	function get_group($uid,&$group){
		$uid = (int)$uid;
		if($uid == 0){
			$g = 6;
		} else {
			$res = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_privilegies WHERE userid = $uid");
			while($row = $this->fetch_array($res)){
				$g = $row['groupid'];
			}
		}
		$group = $g;
	}

	function get_group_name($gid, &$group){
		$res = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."groups WHERE gid = $gid LIMIT 1");
		$row = $this->fetch_array($res);
		$group = $row['name'];
	}

	function check_privilegies($group){
		$res = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."groups WHERE gid = $group");
		while($row = $this->fetch_array($res)){
			$sections = explode(",", $row['sections']);
		}
		/* Check the sections */
		if($sections[0] == '*'){
			$allowed = true;
		} else {
			foreach($sections as $s){
				if($s == KLEO_ACTUAL_MODULE){
					$allowed = true;
				}
			}
		}

		/* If false... APPERROR */
		if(!$allowed && $this->is_logged()){
			$this->apperror(L_INSUFICIENT_PRIVILEGIES, 'common');
		} else if(!$allowed && !$this->is_logged()){
			$this->appredirect("?module=users");
		}
	
	}

	function kleo_login($username, $password, $remember=true){

		/* md5(sha1()) encryption */
		$password = md5(sha1($password));
		$username = htmlspecialchars($username, ENT_QUOTES);

		if(empty($username) or empty($password)){
			$this->apperror(L_USERNAME_OR_PASSWORD_WRONG, 'common');
		}

		$res = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE username = '$username' AND pass = '$password' LIMIT 1");
		if($this->num_rows($res)){
			$row = $this->fetch_array($res);
			$this->get_group($row['uid'],$group);
			$url = $this->get_core_value('siteurl');
			$_SESSION['uid'] = $row['uid'];
			$_SESSION['url'] = $url;
			$_SESSION['user'] = md5($row['password'].$row['salt']);
			$_SESSION['group'] = $group;
			return true;
		} else {
			unset($_SESSION['uid']);
			unset($_SESSION['user']);
			unset($_SESSION['group']);
			$this->unlog_visitor();
			return false;
		}
		if($remember){
			$remember_salt = $this->generate_salt(32);
			$uid = $_SESSION['uid'];
			if(isset($_COOKIE[KLEO_LOGIN_COOKIE_NAME])){
				unset($_COOKIE[KLEO_LOGIN_COOKIE_NAME]);
			}
			$this->new_session($uid,$ip,$remember_salt);
			setcookie(KLEO_LOGIN_COOKIE_NAME, md5($ip.$remember_salt.$url), KLEO_LOGIN_COOKIE_TIME,"","",1); 
		}

	}

	function is_logged(){
		$this->check_user();
		if(isset($_SESSION['user']) && isset($_SESSION['url']) == $this->get_core_value('siteurl')){
			return true;
		} else {
			return false;
		}
	}

	function check_user(){
		if(isset($_COOKIE[KLEO_LOGIN_COOKIE_NAME]) && !isset($_SESSION['user'])){
			$cookie = $_COOKIE[KLEO_LOGIN_COOKIE_NAME];
			$url = $this->get_core_value('siteurl');
			$check_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."sessions WHERE MD5(CONCAT(ip,salt,'$url')) = '$cookie'");
			if($this->num_rows($check_query) !== 0){
				$row = $this->fetch_array($check_query);
				$_SESSION['user'] = true;
				$_SESSION['uid'] = $row['userid'];
				$_SESSION['url'] = $url;
			}

		}
	}

	function new_session($uid,$ip,$remember_salt){
			$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."sessions` (
					`sessid` ,
					`userid` ,
					`ip` ,
					`salt`
				) VALUES (
					NULL , $uid, '$ip', '$remember_salt'
				);
			");
	}

	function is_user($foo){
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE username = '$foo' OR uid = $foo OR email = '$foo' LIMIT 1");
		if($this->num_rows($query) !== 0){
			return true;
		} else {
			return false;
		}	
	}

	function generate_visitor_session(){

		if(!isset($_SESSION['vsess'])){
			$ip = $_SERVER['REMOTE_ADDR'];
			$salt = $this->generate_salt();
 			$browser = $_SERVER['HTTP_USER_AGENT'];
			$_SESSION['vsalt'] = $salt;
			$_SESSION['vsess'] = md5(sha1($ip.$salt));
			$this->query("INSERT INTO ".KLEO_TABLE_PREFIX."statistics_browsers (broname, broip) VALUES ('$browser', '$ip')");
			
		}
		
		$this->appreload();
	}


	function log_visitor(){

		$this->get_os();
		if(!isset($_SESSION['vsess'])){
			$this->generate_visitor_session();
		}

		$ip = $_SERVER['REMOTE_ADDR'];
		$vsess = $_SESSION['vsess'];

		$year = date("Y");
		$month = date("m");
		$day = date("d");
		$hour = date("H");
		$min = date("i");
		$sec = date("s");

		$this->query("INSERT INTO ".KLEO_TABLE_PREFIX."statistics_visitors (vip, vsess, year, month, day, hour, min, sec) VALUES ('$ip', '$vsess', '$year', '$month', '$day', '$hour', '$min', '$sec')");
		
	}

	function unlog_visitor(){
		
		unset($_SESSION['vsalt']);
		unset($_SESSION['vsess']);

	}

	function get_user_info($id){
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users, ".KLEO_TABLE_PREFIX."users_profiles WHERE ".KLEO_TABLE_PREFIX."users.uid = $id AND ".KLEO_TABLE_PREFIX."users_profiles.uid = ".KLEO_TABLE_PREFIX."users.uid LIMIT 1");
		if($this->num_rows($query)){
			$row = $this->fetch_array($query);
			return $row;
		} else {
			return false;
		}
	}

	function add_user($username,$pass,$email,$group=2,$check=0,$status=0,$salt=null){

		if(empty($salt)){
			$salt = $this->generate_salt();
		}

		if($this->get_core_value('email_confirmation') == "yes"){
			$status = 0;
		} else {
			$status = 1;
		}

		$pass = md5(sha1($pass));
		$check_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE username = '$username' OR email = '$email'");
		if($this->num_rows($check_query) == 0){
			if($check == 0){
				$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."users` (
						`uid` ,
						`username` ,
						`pass` ,
						`email` ,
						`salt` ,
						`status`
					) VALUES (
						NULL , '$username', '$pass', '$email', '$salt', '$status'
					);
				");
				$get_query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users ORDER BY uid DESC LIMIT 1");
				$get_row = $this->fetch_array($get_query);
				$last_id = $get_row['uid'];
				$this->query("INSERT INTO `".KLEO_TABLE_PREFIX."users_privilegies` (
						`prid` ,
						`userid` ,
						`groupid`
					) VALUES (
						NULL , '$last_id', '$group'
				);");
				if($this->get_core_value('email_confirmation') == "yes"){
					$username = $get_row['username'];
						$hash = md5($get_row['salt']);
					$message = L_CONFIRMATION_EMAIL_MESSAGE.$this->get_core_value('siteurl').'/?module=users&action=activate&activate='.$hash.'&username='.$username;
					$this->sendmail($email, L_CONFIRMATION_EMAIL, $message);
				}
			}
		} else {
			return false;
		}
		
	}

	function activate_user($id,$hash,$user){
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE uid = $id AND MD5(salt) = '$hash' AND username = '$user'");
		if($this->num_rows($query) !== 0){
			$this->query("UPDATE ".KLEO_TABLE_PREFIX."users SET status = 1 WHERE uid = $id LIMIT 1 ;");
			return true;
		} else {
			return false;
		}
	}

	function is_registered_user($username,$email){
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE username = '$username' OR email = '$email'");
		if($this->num_rows($query)){
			return true;
		} else {
			return false;
		}
	}

	function user_has_profile($uid){
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users WHERE uid = $uid");
		if($this->num_rows($query)){
			return true;
		} else {
			return false;
		}
	}
	function calculate_age($date){
		$date = $this->cleandate($date);
		$now = $this->cleandate($this->get_date());
		return (int)substr($now-$date,0,2);
	}

	function get_last_track($user){
		require_once KLEO_LIB_DIR.'third_party/lastfm/lastfmapi.php';
		$authVars['apiKey'] = 'fa3af76b9396d0091c9c41ebe3c63716';
		$auth = new lastfmApiAuth('setsession', $authVars);
		$apiClass = new lastfmApi();
		$userClass = $apiClass->getPackage($auth, 'user');
		$methodVars = array(
			'user' => $user
		);
		if ( $tracks = $userClass->getRecentTracks($methodVars) ) {
			return $tracks[0]['artist']['name'].' - '.$tracks[0]['name'];
		} else { 
			return false;
		}
	}

	function get_last_twit($user){
		if(strlen($user) > 2){
			$this->apploadlib(KLEO_LIB_DIR."twitter.lib.php", "twitter", $twitter);
			$twitter->username = $user;
			$timeline = $twitter->userTimeline($twitter->get_user_id($user),1);
			return $timeline->status;
		} else {
			return false;
		}
	}


	function get_social_bookmarks($uid){
		$buff;
		$query = $this->query("SELECT * FROM ".KLEO_TABLE_PREFIX."users_profiles WHERE uid = $uid LIMIT 1");
		$row = $this->fetch_array($query);
		if(!empty($row['delicious'])){
			$buff .= '<a href="http://delicious.com/'.$row['delicious'].'" title="Delicious"><img src="'.KLEO_SITEURL.'/media/icons/'.KLEO_CURRENT_ICONS.'/16x16/places/delicious.png" /></a> ';
		}
		if(!empty($row['facebook'])){
			$buff .= '<a href="http://facebook.com/'.$row['facebook'].'" title="Facebook"><img src="'.KLEO_SITEURL.'/media/icons/'.KLEO_CURRENT_ICONS.'/16x16/places/facebook.png" /></a> ';
		}
		if(!empty($row['lastfm'])){
			$buff .= '<a href="http://www.last.fm/user/'.$row['lastfm'].'" title="Last.fm"><img src="'.KLEO_SITEURL.'/media/icons/'.KLEO_CURRENT_ICONS.'/16x16/places/lastfm.png" /></a> ';
		}
		if(!empty($row['digg'])){
			$buff .= '<a href="http://digg.com/users/'.$row['digg'].'" title="Digg"><img src="'.KLEO_SITEURL.'/media/icons/'.KLEO_CURRENT_ICONS.'/16x16/places/digg.png" /></a> ';
		}
		if(!empty($row['twitter'])){
			$buff .= '<a href="http://twitter/'.$row['twitter'].'" title="Twitter"><img src="'.KLEO_SITEURL.'/media/icons/'.KLEO_CURRENT_ICONS.'/16x16/places/twitter.png" /></a> ';
		}
		return $buff;
	}

}

?>
